package cn.maihe.elg.operation.centers.fuzhou.handler.service;

import cn.maihe.elg.operation.centers.fuzhou.config.FZMakeInfoConfig;
import cn.maihe.elg.operation.centers.fuzhou.dto.FZBaseRespDTO;
import cn.maihe.elg.operation.centers.fuzhou.dto.handler.FZCheckGuaranteeReqDTO;
import cn.maihe.elg.operation.centers.fuzhou.dto.handler.FZCheckGuaranteeRespDTO;
import cn.maihe.elg.operation.centers.fuzhou.dto.handler.FZInspectionGuaranteeRespDTO;
import cn.maihe.elg.operation.centers.fuzhou.dto.handler.vo.FZBondInspectionDTO;
import cn.maihe.elg.operation.centers.fuzhou.handler.FZCenterTradeService;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.model.enums.*;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeAttachmentInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeDO;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDO;
import cn.maihe.elg.operation.service.business.ProjectInfoService;
import cn.maihe.elg.operation.service.guarantee.GuaranteeService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.ApplyOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.service.order.RefundOrderInfoService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.KTOfdCloudSignService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.VerifySealRespDTO;
import cn.maihe.elg.operation.supports.guarantee.enums.RespCode;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * @Description 保函验真申请 2.6
 * @Author alan
 * @Date 2025/02/25.
 */
@CenterTradeService(
        provider = CenterProviderEnum.ESB_FUZHOU,
        centerNo = CenterNoEnum.FUZHOU,
        tradeType = TradeType.checkTrue,
        reqClass = FZCheckGuaranteeReqDTO.class,
        respClass = FZCheckGuaranteeRespDTO.class
)
@Slf4j
public class FZInspectGuaranteeService extends FZCenterTradeService<FZCheckGuaranteeReqDTO, FZInspectionGuaranteeRespDTO> {

    @Resource
    ApplyOrderInfoService applyOrderInfoService;
    @Resource
    AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    RefundOrderInfoService refundOrderInfoService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private KTOfdCloudSignService KTOfdCloudSignService;

    @Autowired
    private GuaranteeAttachmentInfoService attachment;

    @Autowired
    private ElgResourceService elgResourceService;

    @Resource
    private GuaranteeService guaranteeService;

    public FZInspectGuaranteeService(FZMakeInfoConfig centerInfosConfig) {
        super(centerInfosConfig);
    }


    /**
     * 具体业务处理
     *
     * @param context
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FZInspectionGuaranteeRespDTO processService(CenterTradeContext<FZCheckGuaranteeReqDTO, FZInspectionGuaranteeRespDTO> context) {

        FZCheckGuaranteeReqDTO req = context.getReq();
        Long centerId = context.getCenterId();
        Long orgId = context.getOrgId();
        //todo:alan待保存到本地使用文件进行验签
//        MultipartFile ofdFile = context.getAttr("guarantee_pdf");

        Assert.hasText(req.getSerialNum(), () -> "serialNum不能为空");
        GuaranteeDO guaranteeDO = guaranteeService.getGuaranteeBySerialNum(req.getSerialNum());

        AcceptOrderInfoDO orderInfo = acceptOrderInfoService.getByGuaranteeNo(centerId, orgId, guaranteeDO.getGuaranteeNo());
        if ((orderInfo == null) || (orderInfo.getStatus() < AcceptOrderStatus.HAS_OUT_GUARANTEE.getStatus())) {
            FZInspectionGuaranteeRespDTO result = FZInspectionGuaranteeRespDTO.success("验真失败", FZInspectionGuaranteeRespDTO.class);
            result.setCode(RespCode.FAILURE.getRespCode());
            return result;
        }

//        ProjectInfoDO projectInfoDO = projectInfoService.selectById(orderInfo.getProjectId());
//        GuaranteeDO guarantee = guaranteeService.getGuaranteeByAcceptOrderNo(orderInfo.getAcceptOrderNo());

        GuaranteeAttachmentInfoDO typeAttachmentByAcceptOrderNo = attachment.getTypeAttachmentByAcceptOrderNo(orderInfo.getAcceptOrderNo(), AttachmentFileType.TYPE_0);
        Path filePath = elgResourceService.getAbsolutePath(typeAttachmentByAcceptOrderNo.getFilePath());

        List<VerifySealRespDTO> verifySealRespDTOS;
        try {
            verifySealRespDTOS = KTOfdCloudSignService.ofdVerifySeal(orderInfo.getAcceptOrderNo(), filePath);
            if (verifySealRespDTOS.isEmpty()) {
                FZInspectionGuaranteeRespDTO result = FZInspectionGuaranteeRespDTO.success("保函验真", FZInspectionGuaranteeRespDTO.class);
                result.setCode(RespCode.CHECK_FALSE.getRespCode());
                return result;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 默认先获取第一个数据
        VerifySealRespDTO verifySealRespDTO = verifySealRespDTOS.get(0);

        FZBondInspectionDTO fzBondCheckDTO = new FZBondInspectionDTO();
        fzBondCheckDTO.setSerialNum(guaranteeDO.getSerialNum());
        fzBondCheckDTO.setSignName(verifySealRespDTO.getSealName());

        Date date = DateUtil.parseString2UTCDate(verifySealRespDTO.getSignTime());

        fzBondCheckDTO.setSignTime(DateUtil.formateDate(date, "yyyy-MM-dd HH:mm:ss"));
        // 先默认凯特
        fzBondCheckDTO.setIssuer("福建省电子印章服务平台");
        // 先默认凯特
        fzBondCheckDTO.setIsModified("2");


        FZInspectionGuaranteeRespDTO respDTO = FZInspectionGuaranteeRespDTO.success("验真完成", FZInspectionGuaranteeRespDTO.class);
        respDTO.setData(fzBondCheckDTO);
        respDTO.setStatus("200");
        return respDTO;
    }

}

